#include <iostream>
#include <crtdbg.h>

using namespace std;
// 智能指针实现原理：
// 1. RAII--->作用：自动释放资源
// 2. 具有指针类似行为：operator*()   operator->()
// 3. 解决浅拷贝的方式
template<class T>
class SmartPtr
{
public:
    // RAII
    SmartPtr(T* ptr = nullptr)
            : _ptr(ptr)
    {}

    ~SmartPtr()
    {
        if (_ptr)
        {
            delete _ptr;
            _ptr = nullptr;
        }
    }


    /////////////////////////////////////
    // 具有指针类似的操作
    T& operator*()
    {
        return *_ptr;
    }

    T* operator->()
    {
        return _ptr;
    }

private:
    T* _ptr;
};
struct A
{
    int a;
    int b;
    int c;
};

void TestSmartPtr()
{
    int* p = new int;
    *p = 100;
    delete p;

    A* pa = new A;
    pa->a = 10;
    delete pa;

    SmartPtr<int> sp(new int);
    *sp = 100;

    SmartPtr<A> sp2(new A);
    sp2->a = 100;

    SmartPtr<A> sp3(sp2);
}

int main(){
    TestSmartPtr();
    _CrtDumpMemoryLeaks();
    return 0;
}
